/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client;
import java.io.*;
import java.net.*;
/**
 *
 * @author LazyTran
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        // Client Program
        try{
            String stSend;
            String stRcv;
            boolean sExit,rExit;
            //khoi tao socket
            DatagramSocket socket =new DatagramSocket();
            int port = 1234;
            //Gan dia chi IP va port vao InetAddress
            //InetAddress ipServer= InetAddress.getByName("localhost");
            InetAddress ipServer = InetAddress.getByAddress("127.0.0.1", new byte[]{127, 0, 0, 1});
            
            
            do {
                //Goi thong diep cho Server
                byte []sendData = new byte[1024];
                BufferedReader in =new BufferedReader(new InputStreamReader(System.in) );
                System.out.print("Client: ");
                stSend = in.readLine();
                sendData = stSend.getBytes();
                //Khoi tao DatagramPacket
                DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,ipServer,port);
                //Send DatagramPacket
                socket.send(sendPacket);

                //Nhan thong diep tu Server
                byte []rcvbuf = new byte[1024];
                //Khoi tao DatagramPacket de nhan data
                DatagramPacket rcvpkt = new DatagramPacket(rcvbuf,rcvbuf.length);
                //Goi ham nhan data
                socket.receive(rcvpkt);
                stRcv = new String(rcvpkt.getData(),0,rcvpkt.getLength());
                System.out.println("Server: "+ stRcv);

                sExit = (stSend.compareTo("Exit") != 0);
                rExit = (stRcv.compareTo("Exit") != 0);
             } while(sExit && rExit);
            //dong DatagramSocket
            socket.close();

        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

}
